package com.offics.loan.interfaces.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.offics.loan.application.dto.file.FileUploadResponse;
import com.offics.loan.application.dto.user.*;
import com.offics.loan.application.service.UserApplicationService;
import com.offics.loan.infrastructure.common.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户控制器
 */
@Tag(name = "用户", description = "用户相关接口")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
@SecurityRequirement(name = "JWT")
public class UserController {

    private final UserApplicationService userApplicationService;

    /**
     * 获取用户信息
     *
     * @param userId 用户ID
     * @return 用户信息
     */
    @Operation(summary = "获取用户信息", description = "获取用户信息")
    @GetMapping("/{userId}")
    public Result<UserInfoResponse> getUserInfo(@PathVariable Long userId) {
        UserInfoResponse response = userApplicationService.getUserInfo(userId);
        return Result.success(response);
    }

    /**
     * 更新用户信息
     *
     * @param updateUserInfoRequest 更新用户信息请求
     * @return 是否成功
     */
    @Operation(summary = "更新用户信息", description = "更新用户信息")
    @PutMapping
    public Result<Void> updateUserInfo(@Valid @RequestBody UpdateUserInfoRequest updateUserInfoRequest) {
        boolean result = userApplicationService.updateUserInfo(updateUserInfoRequest);
        return result ? Result.success() : Result.failure("更新用户信息失败");
    }

    /**
     * 更新用户信息
     *
     * @param updateUserInfoRequest 更新用户信息请求
     * @return 是否成功
     */
    @Operation(summary = "更新用户信息", description = "更新用户信息")
    @PostMapping("/info")
    public Result<UserInfoResponse> updateUserInfoAndReturn(@Valid @RequestBody UpdateUserInfoRequest updateUserInfoRequest) {
        UserInfoResponse response = userApplicationService.updateUserInfoAndReturn(updateUserInfoRequest);
        return Result.success(response);
    }

    /**
     * 修改密码
     *
     * @param changePasswordRequest 修改密码请求
     * @return 是否成功
     */
    @Operation(summary = "修改密码", description = "修改密码")
    @PutMapping("/password")
    public Result<Void> changePassword(@Valid @RequestBody ChangePasswordRequest changePasswordRequest) {
        boolean result = userApplicationService.changePassword(changePasswordRequest);
        return result ? Result.success() : Result.failure("修改密码失败");
    }

    /**
     * 重置密码
     *
     * @param resetPasswordRequest 重置密码请求
     * @return 是否成功
     */
    @Operation(summary = "重置密码", description = "重置密码")
    @PutMapping("/password/reset")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> resetPassword(@Valid @RequestBody ResetPasswordRequest resetPasswordRequest) {
        boolean result = userApplicationService.resetPassword(resetPasswordRequest);
        return result ? Result.success() : Result.failure("重置密码失败");
    }

    /**
     * 分页查询用户
     *
     * @param pageRequest 分页请求
     * @return 分页结果
     */
    @Operation(summary = "分页查询用户", description = "分页查询用户")
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<IPage<UserInfoResponse>> page(UserPageRequest pageRequest) {
        IPage<UserInfoResponse> page = userApplicationService.page(pageRequest);
        return Result.success(page);
    }

    /**
     * 启用用户
     *
     * @param userId 用户ID
     * @return 是否成功
     */
    @Operation(summary = "启用用户", description = "启用用户")
    @PutMapping("/{userId}/enable")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> enable(@PathVariable Long userId) {
        boolean result = userApplicationService.enable(userId);
        return result ? Result.success() : Result.failure("启用用户失败");
    }

    /**
     * 禁用用户
     *
     * @param userId 用户ID
     * @return 是否成功
     */
    @Operation(summary = "禁用用户", description = "禁用用户")
    @PutMapping("/{userId}/disable")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> disable(@PathVariable Long userId) {
        boolean result = userApplicationService.disable(userId);
        return result ? Result.success() : Result.failure("禁用用户失败");
    }

    /**
     * 删除用户
     *
     * @param userId 用户ID
     * @return 是否成功
     */
    @Operation(summary = "删除用户", description = "删除用户")
    @DeleteMapping("/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> delete(@PathVariable Long userId) {
        boolean result = userApplicationService.delete(userId);
        return result ? Result.success() : Result.failure("删除用户失败");
    }

    /**
     * 上传文件
     *
     * @param file 文件
     * @param fileType 文件类型（例如：idCardFront, idCardBack, idCardHand）
     * @param userId 用户ID
     * @return 文件上传响应
     */
    @Operation(summary = "上传文件", description = "上传用户相关文件，如身份证照片等")
    @PostMapping("/{userId}/upload")
    public Result<FileUploadResponse> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("fileType") String fileType,
            @PathVariable Long userId) {
        FileUploadResponse response = userApplicationService.uploadFile(file, fileType, userId);
        return Result.success(response);
    }
}
